import { useUser } from "@/stores/useUser";

let isUserInited = false; // 用户是否已完成初始化
// 初始化用户
export const userInit = ({ token }: { token: string }) => {
	return new Promise(async (resolve, reject) => {
		const userStore = useUser();
		userStore.setState({ token: token || localStorage.getItem("token") || "" });
		if (userStore.token) {
			userStore
				.syncToken()
				.then(async () => {
					await userStore.syncUserInfo();
					isUserInited = true;
					resolve(null);
				})
				.catch(() => reject());
		} else reject();
	});
};
// 已登录钩子
export const onUserInited = () => {
	return new Promise((resolve) => {
		fn();
		function fn() {
			if (isUserInited) resolve(null);
			else setTimeout(() => fn(), 500);
		}
	});
};
